package net.togogo.controller;


import net.togogo.entity.TbOrder;
import net.togogo.entity.TbProduct;
import net.togogo.service.TbOrderService;
import net.togogo.service.TbProductService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author qmk
 * @since 2019-10-23
 */
@RestController
@RequestMapping("/order")
public class TbOrderController {

    @Autowired
    TbOrderService orderService;

    @Autowired
    TbProductService productService;

    //消费
    @PostMapping("/generate")
    public String generate(@RequestBody TbOrder order){
        TbProduct product = productService.selectById(order.getProductId());
        String errorMsg = checkProduct(product, order.getNum());
        if (!StringUtils.isEmpty(errorMsg)){
            return errorMsg;
        }

        //扣除库存
        product.setStock(product.getStock() - order.getNum());
        productService.updateById(product);

        //生成订单
        //总量
        int orderCount = orderService.selectCount(null);
        //累计+1
        String no = String.format("%04d", orderCount + 1);
        //订单号
        String orderno = "QMK" + no;
        order.setOrderNo(orderno);

        //保存订单
        orderService.insert(order);
        return orderno;
    }

    //检查订单 num 购买的数量
    public String checkProduct(TbProduct product,int num){
        if (product ==null){
            return "商品不存在！请重新选择";
        }
        if (product.getStock() < num){
            return "商品： " + product.getProductName() + " 库存不足";
        }
        return null;
    }

    //查询所有订单
    @GetMapping("/findAll")
    public List<TbOrder> findAll(){
        return orderService.selectList(null);
    }
}

